package org.sucri.servlet.controller;

import org.sucri.floxs.servlet.User;
import org.sucri.floxs.Tools;
import org.sucri.dao.JPA_Util;
import org.sucri.dao.UsersEntity;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.annotations.RemoteMethod;

import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;
import java.util.Map;

/** The gateway to allow centerilized DWR access
 * Created by IntelliJ IDEA.
 * User: Wen Yu
 * Date: Dec 23, 2007
 * Time: 12:03:58 PM
 * To change this template use File | Settings | File Templates.
 */
@RemoteProxy(name="Admin")
public class dwrAdmin
{
  protected EntityManagerFactory emf;

  public dwrAdmin() { emf = Persistence.createEntityManagerFactory("vpp"); }
  public dwrAdmin(EntityManagerFactory s) { emf = s; }
  public dwrAdmin(String db) { emf = Persistence.createEntityManagerFactory(db); }

  @RemoteMethod
  public ListRange<UsersEntity> getUsers(String user, boolean paging)
  {
    return new ListRange(JPA_Util.get(emf, "select e from UsersEntity e"));    
  }
  @RemoteMethod
  public void updateUsers(UsersEntity[] users, String[] flags)
  {
    if (!Tools.good(users) || !Tools.good(flags) || users.length != flags.length) return;
    for (int i = 0; i < users.length; i++)
    {
      if      (flags[i].equals("u")) JPA_Util.merge( emf, users[i]);
      else if (flags[i].equals("d")) JPA_Util.remove(emf, users[i]);
    }
  }
  @RemoteMethod
  public UsersEntity getUser(Long id)
  {
    return id != null ? (UsersEntity )JPA_Util.get(emf, "select e from UsersEntity e where e.id = " + id).get(0) : null;    
  }
  @RemoteMethod
  //public void setUser(UsersEntity s)
  public void setUser(UsersEntity user)
  {
    // need to save or update the user object
    System.out.println(user.toString());
    if (user.getId() > 0) JPA_Util.merge(emf, user); else JPA_Util.persist(emf, user);
  }
  //@RemoteMethod
 // public void removeUser(UsersEntity s)
  //{
    // need to save or update the user object
    //System.out.println(s.toString());
    //JPA_Util.remove(emf, s);
  //}
  // public ListRange getUsers(int start, int count, String orderBy)
  
}
